package com.workman.controller;

import com.workman.common.util.MD5;
import com.workman.common.util.StringUtil;
import com.workman.common.util.WorkManConstans;
import com.workman.model.User;
import com.workman.model.vo.front.Results;
import com.workman.service.UserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/account")
public class AccountController {
    private Logger logger = LoggerFactory.getLogger(AccountController.class);

    @Autowired
    UserService userService;

    /**
     * 用户登录<br>
     * 1，验证没有注册<br>
     * 2，验证密码错误<br>
     * 3，登录成功
     *
     * @param loginName
     * @param password
     * @return
     */
    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public Object login(@RequestParam("loginName") String loginName,
                        @RequestParam("password") String password) {

        try {
            logger.info("--loginName-{0}---password-{1}",loginName, password);
            if (StringUtil.isNullOrEmpty(loginName) || StringUtil.isNullOrEmpty(password)) {
                return Results.failure("loginName or password can't empty !");
            }
            User user = userService.selectUserByLoginName(loginName);
            if (user == null) {
                return Results.failure("user not exist!");
            }
            if (WorkManConstans.USER_STATUS_FREEZED.equals(user.getStatus())){
                return Results.failure("user freezed!");
            }
            if (WorkManConstans.USER_STATUS_DELETE.equals(user.getStatus())){
                return Results.failure("user deleted!");
            }
            String md5Password = MD5.md5(password, user.getSalt());
            if (!password.equals(md5Password)){
                return Results.failure("password  error!");
            }



            return Results.success();
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }


        return null;
    }


}
